//使用KOA框架
const Koa = require('koa');
//加载path模块
const path = require('path');
//实例化koa
const app = new Koa();

//生产环境
//app.env = 'production';

//配置文件
const config = require('./config');

//static中间件
const static = require('koa-static');

//bodyParser中间件
const bodyParser = require('koa-bodyparser');

//request中间件
const request = require('./middleware/request');

//response中间件
const response = require('./middleware/response');

//try/catch中间件
const errorHandle = require('./middleware/errorHandle');

//引入路由
const router = require('./route');

//initMysql中间件
const initMysql = require('./middleware/initMysql');

//输出请求的方法，url,和所花费的时间
app.use(async(ctx, next) => {
    let start = new Date();
    await next();
    let ms = new Date() - start;
    console.log(`${ ctx.method } ${ ctx.url } - ${ ms } ms`);
});

//使用errorHandle中间件
app.use(errorHandle);

//使用bodyParser中间件
app.use(bodyParser());

//使用koa-static中间件
app.use(static(path.join(__dirname, 'static')));

//使用response中间件
app.use(response);

//使用request中间件
app.use(request);

//使用initMysql中间件
app.use(initMysql);

//使用路由中间件
app.use(router.routes()).use(router.allowedMethods());

//监听端口
app.listen(config.app.port, () => {
    console.log('The server is running at http://localhost:' + config.app.port);
});